package com.example.friend.dao;

import java.sql.*;

import com.example.feiend.utils.JDBCUtils;
import com.example.friend.pojo.User;

public class UserDAO {

	public int insert(User user) throws SQLException {
		// 1. 获取连接
		Connection conn = JDBCUtils.getConnection();

		// 2. 创建Statment
		String sql = "insert into user values (null,?,?,?,?,?,?,?,?,?,?)";
		PreparedStatement stmt = conn.prepareStatement(sql);

		stmt.setString(1, user.getUsername());
		stmt.setString(2, user.getPassword());
		stmt.setString(3, user.getGender());
		stmt.setString(4, user.getStatus());
		stmt.setString(5, user.getBirthday());
		stmt.setString(6, user.getTel());
		stmt.setString(7, user.getQq());
		stmt.setInt(8, user.getAge());
		stmt.setString(9, user.getLike());
		stmt.setString(10, user.getIntro());

		// 3. 执行层语句
		int result = stmt.executeUpdate();

		// 4. 释放资源
		JDBCUtils.destory(conn, stmt, null);

		return result;

	}

	public User findBy(String username, String password) throws SQLException {
		// 1. 获取连接
		Connection conn = JDBCUtils.getConnection();

		// 2. 创建Statment
		String sql = "select * from user where username=? and password=?";
		PreparedStatement stmt = conn.prepareStatement(sql);

		stmt.setString(1, username);
		stmt.setString(2, password);

		// 3. 执行层语句
		ResultSet rs = stmt.executeQuery();
		User u = null;
		if(rs.next())
		{
			int id = rs.getInt(1);// 通过列号获取
			int age = rs.getInt("age");// 通过列的字段名获取
			String like = rs.getString("like");
			
			u = new User();
			u.setId(id);
			u.setUsername(username);
			u.setAge(age);
			u.setLike(like);
		}

		// 4. 释放资源
		JDBCUtils.destory(conn, stmt, null);

		return u;

	}
}